package com.dpj.netty.c3.self_protocol.protocol;


import com.dpj.netty.c3.self_protocol.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

public class TestMessageCode {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel=new EmbeddedChannel(
                //new LengthFieldBasedFrameDecoder解决粘包 半包 问题
                new LengthFieldBasedFrameDecoder(1024,12,4,0,0)
                ,new LoggingHandler(),(new MessageCode()));
        //encode
        LoginRequestMessage message=new LoginRequestMessage("zhangsan","123");
       channel.writeOutbound(message);

       //decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCode().encode(null,message,buf);

        ByteBuf s1 = buf.slice(0, 100);
        ByteBuf s2 = buf.slice(100, buf.readableBytes()-100);
        //入站 因为我们的buf.slice 是零拷贝，所以他和s1和buf是共用一块内存，当我们调用 channel.writeInbound(s1)时
        //它会清除s1的内存，也就是buf的内存,但是我们的s2还需要这个内存，所以我们就就调用s1.retain()这个方法
        //让它不清除s1，内存
        s1.retain();
        channel.writeInbound(s1);
        channel.writeInbound(s2);
    }
}
